const url_all = {
    'DEV': '/h5api',
    'PRO': 'http://localhost:8080',
};

export const SYSTEM_INFO = uni.getSystemInfoSync();
export const API_HOST = SYSTEM_INFO.uniPlatform;

let BASEURL; // 提升变量声明
if (API_HOST === 'web') {
    BASEURL = url_all['DEV'];
} else {
    BASEURL = url_all['PRO'];
}

export default (path, method, data = {}, loading = true) => {
	// 获取存储token
	const token = uni.getStorageSync("token");
	if (loading) {
		uni.showLoading({
			title: "加载中",
			mask: true
		});
	};
	//根据token进行调用函数
	if (token != '') {
		return tokenRequest(path, method, data, loading, token)
	} else {
		return noTokenRequest(path, method, data, loading)
	}
};

// 无token时发送请求函数
function noTokenRequest(path, method, data, loading) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASEURL + path,
			method: method,
			data,
			success(response) {
				resolve(response.data);
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error(err);
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}


// 有token时发送请求函数
function tokenRequest(path, method, data, loading, token) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASEURL + path,
			method: method,
			data,
			header: {
				"token":  token
			},
			success(response) {
				console.log('%c响应拦截：', ' background:green', response);
				if (response.data.code === 40101) {
					// logout()
				}
				console.log(response.data)
				resolve(response.data);
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error(err);
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}
